document.addEventListener("DOMContentLoaded", () => {
  const settingsForm = document.getElementById(
    "settingsForm"
  ) as HTMLFormElement;
  const openKey = document.getElementById("openKey") as HTMLInputElement;
  const passwd = document.getElementById("passwd") as HTMLInputElement;
  const saveSettings = document.getElementById(
    "saveSettings"
  ) as HTMLButtonElement;
  const shopSelectElement = document.getElementById(
    "shopSelect"
  ) as HTMLButtonElement;

  // 初始化检查登录状态
  checkLoginStatus();

  settingsForm.addEventListener("submit", async function (e) {
    e.preventDefault();
    await handleLogin();
  });

  const automaticallyAgreeToNegotiateElement = document.getElementById(
    "automaticallyAgreeToNegotiate"
  ) as HTMLInputElement;

  const automaticallyAgreeToNegotiateByCostPriceElement =
    document.getElementById(
      "automaticallyAgreeToNegotiateByCostPrice"
    ) as HTMLInputElement;

  // 开始自动同意建议价
  automaticallyAgreeToNegotiateElement.addEventListener("click", () => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs && tabs[0] && tabs[0].id) {
        chrome.tabs.sendMessage(tabs[0]?.id, {
          action: "automaticallyAgreeToNegotiateAction",
        });
      }
    });
  });

  // 开始自动同意建议价
  automaticallyAgreeToNegotiateByCostPriceElement.addEventListener(
    "click",
    () => {
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs && tabs[0] && tabs[0].id) {
          chrome.tabs.sendMessage(tabs[0]?.id, {
            action: "automaticallyAgreeToNegotiateActionByCostPrice",
          });
        }
      });
    }
  );

  shopSelectElement.addEventListener("change", function (event) {
    // 获取选中的值
    const target = event.target as HTMLSelectElement; // 类型断言
    if (target) {
      const selectedValue = target.value;
      chrome.storage.sync.set({
        baoyiplus_shopId: selectedValue,
      });
    }

    // 在这里添加你的业务逻辑
    // 例如：根据选中值请求其他接口、更新页面等
  });

  // 初始化店铺选择
  async function handleInitShopOptions() {
    const storage = await chrome.storage.sync.get([
      "baoyiplus_accessToken",
      "baoyiplus_expiresIn",
      "baoyiplus_username",
    ]);
    // 解构赋值，设置默认值防止undefined
    const {
      baoyiplus_accessToken = "",
      baoyiplus_expiresIn = 0,
      baoyiplus_username = "",
    } = storage;
    if (baoyiplus_accessToken) {
      try {
        shopSelectElement.disabled = true;
        const tempOption = document.createElement("option");
        tempOption.textContent = "加载中...";
        shopSelectElement.innerHTML = "";
        shopSelectElement.appendChild(tempOption);

        // 请求接口数据
        const response = await fetch(
          "https://java.baoyierp.com/api/shop/commonData/selectList/shopInfo",
          {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
              Authorization: "Bearer " + baoyiplus_accessToken,
            },
          }
        );

        const responseData = await response.json();
        const data = responseData.data || [];

        // 清空并重新渲染options
        shopSelectElement.innerHTML = "";

        // 循环添加数据选项
        data.forEach((item: any) => {
          const option = new Option(item.shopName, item.id);
          shopSelectElement.appendChild(option);
        });

        const storage = await chrome.storage.sync.get(["baoyiplus_shopId"]);
        const { baoyiplus_shopId } = storage || {};

        if (baoyiplus_shopId) {
          shopSelectElement.value = baoyiplus_shopId;
        } else {
          const defaultValue = data?.[0]?.id || "";
          shopSelectElement.value = defaultValue;
          chrome.storage.sync.set({
            baoyiplus_shopId: defaultValue,
          });
        }
        // 恢复select可用状态
        shopSelectElement.disabled = false;
      } catch (error) {
        console.error("渲染下拉选项失败:", error);

        // 显示错误状态
        const selectEl = document.querySelector("#shopSelect");
        if (selectEl) {
          selectEl.innerHTML = "";
          const errorOption = new Option("加载失败", "");
          errorOption.disabled = true;
          selectEl.appendChild(errorOption);
        }
      }
    } else {
      await clearLoginData();
      saveSettings.innerHTML = "登录已过期，请重新登录";
      automaticallyAgreeToNegotiateElement.style.display = "none";
      automaticallyAgreeToNegotiateByCostPriceElement.style.display = "none";
    }
  }

  // 检查登录状态函数
  async function checkLoginStatus() {
    const storage = await chrome.storage.sync.get([
      "baoyiplus_accessToken",
      "baoyiplus_expiresIn",
      "baoyiplus_username",
    ]);
    // 解构赋值，设置默认值防止undefined
    const {
      baoyiplus_accessToken = "",
      baoyiplus_expiresIn = 0,
      baoyiplus_username = "",
    } = storage;

    if (baoyiplus_accessToken) {
      const isExpired = checkTokenExpired(baoyiplus_expiresIn);
      if (!isExpired) {
        saveSettings.innerHTML = "登录成功";
        saveSettings.disabled = true;
        // 用户名输入框设置
        openKey.disabled = true;
        openKey.value = baoyiplus_username || "已登录用户";

        openKey.style.backgroundColor = "#f0f0f0"; // 视觉区分

        // 密码框设置
        passwd.disabled = true;
        passwd.value = "********"; // 掩码显示
        passwd.style.backgroundColor = "#f0f0f0";
        // 可选：添加"退出登录"按钮
        if (!document.getElementById("logoutBtn")) {
          const logoutBtn = document.createElement("button");
          logoutBtn.id = "logoutBtn";
          logoutBtn.textContent = "退出登录";
          logoutBtn.style.marginLeft = "10px";
          logoutBtn.onclick = async () => {
            await clearLoginData();
            location.reload(); // 刷新页面恢复登录表单
          };
          settingsForm.appendChild(logoutBtn);
          automaticallyAgreeToNegotiateElement.style.display = "block";
          automaticallyAgreeToNegotiateByCostPriceElement.style.display =
            "block";
          shopSelectElement.style.display = "block";
          handleInitShopOptions();
        }
      } else {
        await clearLoginData();
        saveSettings.innerHTML = "登录已过期，请重新登录";
        automaticallyAgreeToNegotiateElement.style.display = "none";
        automaticallyAgreeToNegotiateByCostPriceElement.style.display = "none";
      }
    }
  }

  // 检查token是否过期（针对时间戳格式）
  function checkTokenExpired(expiresIn: string | number): boolean {
    if (!expiresIn) return true;

    // 统一转换为数字
    const expiryTime =
      typeof expiresIn === "string" ? parseInt(expiresIn) : expiresIn;

    // 获取当前时间戳（毫秒）
    const currentTime = new Date().getTime();
    return currentTime > expiryTime;
  }

  // 清除登录数据
  async function clearLoginData() {
    await chrome.storage.sync.remove([
      "baoyiplus_accessToken",
      "baoyiplus_expiresIn",
      "baoyiplus_shopId",
    ]);
  }

  // 处理登录逻辑
  async function handleLogin() {
    saveSettings.disabled = true;
    saveSettings.innerHTML = "登录中...";

    try {
      const result = await login(openKey, passwd);

      if (result?.code === 0 && result.data) {
        await chrome.storage.sync.set({
          baoyiplus_accessToken: result.data.accessToken,
          baoyiplus_expiresIn: result.data.expiresIn, // 存储原始时间戳
          baoyiplus_username: openKey.value,
        });
        handleInitShopOptions();
        showLoginSuccess();
      } else {
        showLoginError(result?.msg || "登录失败");
      }
    } catch (error) {
      console.error("登录异常:", error);
      showLoginError("网络异常");
    }
  }

  // 显示登录成功状态
  function showLoginSuccess() {
    saveSettings.innerHTML = "登录成功";
    saveSettings.disabled = true;
    automaticallyAgreeToNegotiateElement.style.display = "block";
    automaticallyAgreeToNegotiateByCostPriceElement.style.display = "block";
    location.reload();
  }

  // 显示登录错误状态
  function showLoginError(message: string) {
    saveSettings.innerHTML = message;
    saveSettings.style.color = "red";
    saveSettings.disabled = false;

    setTimeout(() => {
      saveSettings.innerHTML = "点击登录";
      saveSettings.style.color = "";
    }, 2000);
  }

  // 登录API
  async function login(user: HTMLInputElement, passwd: HTMLInputElement) {
    const apiurl = "https://java.baoyierp.com/api/user/login";
    //http://192.168.1.13:5201/api/user/login
    //https://java.baoyierp.com/api/user/login
    const response = await fetch(apiurl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        username: user.value,
        password: passwd.value,
        loginEntrance: "PRICE_CHECK_PLUGIN",
      }),
    });
    return response.json();
  }


  // chrome.runtime.onMessage.addListener((message) => {
  //   if (message.action === "popupUpdate") {
  //     console.log(message)
  //     const { textContent, action, pointerEvents } = message.data || {};
  //     if (action === "updateAutomaticallyAgreeToNegotiateElement") {
  //       automaticallyAgreeToNegotiateElement.textContent = textContent;
  //       automaticallyAgreeToNegotiateElement.style.pointerEvents = pointerEvents;
        
  //     } else if (
  //       action === "updateAutomaticallyAgreeToNegotiateByCostPriceElement"
  //     ) {
  //       automaticallyAgreeToNegotiateByCostPriceElement.textContent = textContent;
  //       automaticallyAgreeToNegotiateByCostPriceElement.style.pointerEvents =
  //         pointerEvents;
  //     }
  //   }
  // });
});
